package com.hns.can.report.web;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hns.can.base.entity.SysOperateLogEntity;
import com.hns.can.base.entity.SysUserEntity;
import com.hns.can.common.domain.GridPage;
import com.hns.can.common.entity.BaseEntity;
import com.hns.can.common.formula.FillCodeDscValue;
import com.hns.can.common.vo.CommonParamsVo;
import com.hns.can.common.web.BaseController;
import com.hns.can.report.service.ReportOperatDateService;
import com.hns.can.report.vo.LogStatisticParamVo;
import com.hns.can.report.vo.OperateLogParamVo;
import com.hns.frame.mybatis.Pagination;
import com.hns.tool.export.ExportUtil;
import com.hns.tool.pub.DateTool;
import com.hns.tool.pub.JsonUtil;
import com.hns.tool.pub.PubUtil;
/**
 * 日志controller
 * @author:zhangyu
 * @email:zhangyu2222z@sina.cn
 * @version Revision 2.0.0
 */
@Controller
@RequestMapping("reportOperatDate")
public class ReportOperatDateController extends BaseController {
	
	@Autowired
	private ReportOperatDateService reportOperatDateService;
	
	@Autowired
    private FillCodeDscValue codeDscValue;
	
	private final String[] detailHeaderName={"操作类型","功能名称","用户帐号","用户名称","所属企业","操作时间","操作url","响应时长","IP地址","ip来源", "MAC地址"};
	private final String[] detailColName={"mnpltType","mnpltFuncName","acctName","userName","corpName","smnpltTime","mnpltUrl","smnpltDura","ipAdr", "ipLocation", "macAdr"};
	
	private final String[] staticHeaderName={"操作类型","操作功能","操作次数","操作人数","平均响应时长"};
	private final String[] staticColName={"mnpltType","funcName","oprCnt","oprUserCnt","avgMnpltDura"};
	
	/**
     * @param conditionVo
     * @param request
     * @param response
     * @throws Exception
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-10-22
     * @功能说明：日志查询，返回page对象
     */
    @RequestMapping("/searchOperateLogPage")
    @ResponseBody
    public Object searchOperateLogPage(OperateLogParamVo conditionVo) throws Exception {
        Pagination page = reportOperatDateService.searchOperateLogPage(conditionVo);
        GridPage grid = new GridPage(page);
        return this.getReturnResult(grid);
    }
    /**
     * 导出日志明细excel
     * @param conditionVo
     * @param response
     * @throws Exception
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @RequestMapping("/exportOperateLogExcel")
    public void exportOperateLogExcel(OperateLogParamVo conditionVo, HttpServletResponse response) throws Exception {
        List<BaseEntity> list = getOperateLogList(conditionVo);
        ExportUtil.exportFiles(Arrays.asList(detailHeaderName), Arrays.asList(detailColName), list, response, "excel", URLEncoder.encode("日志明细", "UTF-8") + DateTool.getCurrentSysDate("yyyyMMddHHmmss"), "日志明细excel");
    }
	/**
	 * 导出日志明细pdf
	 * @param conditionVo
	 * @param response
	 * @throws Exception
	 * @author:zhangyu
	 * @email:zhangyu2222z@sina.cn
	 */
    @RequestMapping("/exportOperateLogPdf")
    public void exportOperateLogPdf(OperateLogParamVo conditionVo, HttpServletResponse response) throws Exception {
        List<BaseEntity> list = getOperateLogList(conditionVo);
        ExportUtil.exportFiles(Arrays.asList(detailHeaderName), Arrays.asList(detailColName), list, response, "pdf", URLEncoder.encode("日志明细", "UTF-8") + DateTool.getCurrentSysDate("yyyyMMddHHmmss"), "日志明细pdf");
    }
    
    /**
     * 导出日志数据
     * @param conditionVo
     * @return
     * @throws Exception
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @SuppressWarnings("unchecked")
	private List<BaseEntity> getOperateLogList(OperateLogParamVo conditionVo) throws Exception{
    	List list = reportOperatDateService.getOperateLogList(conditionVo);
    	Map<String,String> tmpMap = new HashMap<String,String>();
        tmpMap.put("mnpltType", "OLOG0000");
        codeDscValue.fillCodeDscValue(list, tmpMap);
        HashMap ipAdrMap = new HashMap();
        for(Object obj : list){
        	SysOperateLogEntity entity = (SysOperateLogEntity)obj;
        	String ipLocation = "";
        	if(PubUtil.isEmpty(ipAdrMap.get(entity.getIpAdr()))){
        		ipLocation = getIpAdr(entity.getIpAdr());
        		ipAdrMap.put(entity.getIpAdr(), ipLocation);
        	}else{
        		ipLocation = (String)ipAdrMap.get(entity.getIpAdr());
        	}
        	entity.setIpLocation(ipLocation);
        }
    	return list;
    }
	
    /**
     * 日志统计
     * @param conditionVo
     * @param request
     * @param response
     * @throws Exception
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @RequestMapping("/searchOperateLogStaticPage")
    @ResponseBody
    public Object searchOperateLogStaticPage(LogStatisticParamVo conditionVo, HttpServletRequest request, 
                HttpServletResponse response) throws Exception {
        SysUserEntity user = this.getCurrentUser().getUser();
        conditionVo.setCorpId(user.getCorpId());
        Pagination page = reportOperatDateService.searchLogStatisticPage(conditionVo);
        GridPage grid = new GridPage(page);
        return this.getReturnResult(grid);
    }
    
    /**
     * 导出日志明细excel
     * @param conditionVo
     * @param response
     * @throws Exception
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @RequestMapping("/exportOperateLogStaticExcel")
    public void exportOperateLogStaticExcel(LogStatisticParamVo conditionVo, HttpServletResponse response) throws Exception {
        List list = getOperateLogStaticList(conditionVo);
        ExportUtil.exportFiles(Arrays.asList(staticHeaderName), Arrays.asList(staticColName), list, response, "excel", URLEncoder.encode("日志统计", "UTF-8") + DateTool.getCurrentSysDate("yyyyMMddHHmmss"), "日志统计导出excel");
    }
	/**
	 * 导出日志明细pdf
	 * @param conditionVo
	 * @param response
	 * @throws Exception
	 * @author:zhangyu
	 * @email:zhangyu2222z@sina.cn
	 */
    @RequestMapping("/exportOperateLogStaticPdf")
    public void exportOperateLogStaticPdf(LogStatisticParamVo conditionVo, HttpServletResponse response) throws Exception {
        List list = getOperateLogStaticList(conditionVo);
        ExportUtil.exportFiles(Arrays.asList(staticHeaderName), Arrays.asList(staticColName), list, response, "pdf", URLEncoder.encode("日志统计", "UTF-8") + DateTool.getCurrentSysDate("yyyyMMddHHmmss"), "日志统计导出pdf");
    }
    
    /**
     * 导出日志数据
     * @param conditionVo
     * @return
     * @throws Exception
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    private List getOperateLogStaticList(LogStatisticParamVo conditionVo) throws Exception{
    	SysUserEntity user = this.getCurrentUser().getUser();
        conditionVo.setCorpId(user.getCorpId());
    	List list = reportOperatDateService.getLogStatisticList(conditionVo);
    	Map<String,String> tmpMap = new HashMap<String,String>();
        tmpMap.put("mnpltType", "OLOG0000");
        codeDscValue.fillCodeDscValue(list, tmpMap);
    	return list;
    }
    
    
    @SuppressWarnings("rawtypes")
	@RequestMapping("/getLogColltTable")
    @ResponseBody
    public Object getLogColltTable(CommonParamsVo vo,
    		HttpServletRequest request, HttpServletResponse response){
    	List list = reportOperatDateService.getLogColltTable(vo);
    	return this.getReturnResult(list);
    }
    
    @SuppressWarnings("rawtypes")
	@RequestMapping("/getUsersAccessCollection")
    @ResponseBody
    public Object getUsersAccessCollection(CommonParamsVo vo,
    		HttpServletRequest request, HttpServletResponse response){
    	List list = reportOperatDateService.getUsersAccessCollection(vo);
    	return this.getReturnResult(list);
    }
    
    @SuppressWarnings("rawtypes")
    @RequestMapping("/getDistributionByFunc")
    @ResponseBody
	public Object getDistributionByFunc(CommonParamsVo vo,
    		HttpServletRequest request, HttpServletResponse response){
    	List list = reportOperatDateService.getDistributionByFunc(vo);
    	return this.getReturnResult(list);
    }
    
    @SuppressWarnings("rawtypes")
    @RequestMapping("/getUsersAccessRateByDays")
    @ResponseBody
	public Object getUsersAccessRateByDays(CommonParamsVo vo,
    		HttpServletRequest request, HttpServletResponse response){
    	List list = reportOperatDateService.getUsersAccessRateByDays(vo);
    	return this.getReturnResult(list);
    }
    
    @SuppressWarnings("rawtypes")
    @RequestMapping("/getUsersAccessRateByHours")
    @ResponseBody
	public Object getUsersAccessRateByHours(CommonParamsVo vo,
    		HttpServletRequest request, HttpServletResponse response){
    	List list = reportOperatDateService.getUsersAccessRateByHours(vo);
    	return this.getReturnResult(list);
    }
    
    @SuppressWarnings("rawtypes")
    @RequestMapping("/getTop10OfQuery")
    @ResponseBody
    public Object getTop10OfQuery(CommonParamsVo vo,
    		HttpServletRequest request, HttpServletResponse response){
    	List list = reportOperatDateService.getTop10OfQuery(vo);
    	return this.getReturnResult(list);
    }
    
    @SuppressWarnings("rawtypes")
    @RequestMapping("/getTop10OfFunc")
    @ResponseBody
    public Object getTop10OfFunc(CommonParamsVo vo,
    		HttpServletRequest request, HttpServletResponse response){
    	List list = reportOperatDateService.getTop10OfFunc(vo);
    	return this.getReturnResult(list);
    }
    
    private String getIpAdr(String ip){
    	URL url;
    	String ipAdr = "";
		try {
			url = new URL("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip="+ip);
			HttpURLConnection urlcon = (HttpURLConnection)url.openConnection();
			urlcon.connect();         //获取连接
			InputStream is = urlcon.getInputStream();
			BufferedReader buffer = new BufferedReader(new InputStreamReader(is));
			StringBuffer bs = new StringBuffer();
			String l = null;
			while((l=buffer.readLine())!=null){
				bs.append(l);
			}
			if(bs.length() > 21){
				Map map = JsonUtil.getMapFromJsonString(bs.substring(21, bs.length()-1));
				if(PubUtil.isEmpty(map.get("country")) || PubUtil.isEmpty(map.get("province")) || PubUtil.isEmpty(map.get("city"))){
					ipAdr = "未知";
				}else{
					ipAdr = map.get("country") +"-"+ map.get("province") +"-"+ map.get("city") ;
				}
			}else{
				ipAdr = "未知";
			}
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return ipAdr;
    }
    
    
}
